package com.haiwen.boot.service.Aspect;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.haiwen.boot.mapper.LogMapper;
import com.haiwen.boot.pojo.Log;
import com.haiwen.boot.utils.IPUtil;
import com.haiwen.boot.utils.RedisUtil;
import com.haiwen.boot.utils.UserContext;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@Aspect
@Component
public class LogAspect {
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private LogMapper logMapper;

    @Pointcut("execution(* * ..service.lmpl.*.*(..))")
    public void ServiceLog(){ }

    @Around("ServiceLog()")
    public Object Log(ProceedingJoinPoint pjp) {
        try {
            Log log=new Log();
            log.setLogTime(new Date());
            String className = pjp.getTarget().toString();
            String functionName = pjp.getSignature().toString();
            String ClassFunctionName=className + ":" + functionName;
            log.setLogFunction(ClassFunctionName);
            Object o =  pjp.proceed();
            String username = UserContext.get();
            if (username==null){
                log.setLogUser("0");
            }
            log.setLogUser(username);
            String ipAddress = (String)redisUtil.get("ipAddress");
            redisUtil.remove("ipAddress");
            log.setLogIp(ipAddress);

            ObjectMapper objectMapper = new ObjectMapper();
            String Params = objectMapper.writeValueAsString(pjp.getArgs());
            log.setLogParams(Params);
            logMapper.insertSelective(log);
            return o;
        } catch (Throwable e) {
            e.printStackTrace();
            return null;
        }
    }
}
